package middleware

import (
	"github.com/gin-gonic/gin"
	"shopstar/core/cache"
	"shopstar/global"
	"shopstar/reponse"
)

func SmsCodeVerification() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 取key的值
		key := ctx.PostForm("verification_key")
		// 判断在缓存中是否过期  和 验证码是否匹配
		code, err := cache.CacheManager.Get(key)
		if err != nil || string(code.([]byte)) != ctx.PostForm("sms_code") {
			reponse.FailWithErr(global.ErrValidateSmsCode, ctx)
			ctx.Abort()
			return
		}
		// 验证成功
		cache.CacheManager.Delete(key)
		ctx.Next()
	}
}

func CaptchaVerification() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		captchaId := ctx.PostForm("captcha_id")
		captchaCode := ctx.PostForm("captcha_code")
		if captchaId == "" || captchaCode == "" {
			reponse.FailWithErr(global.ErrValidateCaptche, ctx)
			ctx.Abort()
			return
		}

		// 验证验证码是否正确
		if !global.CaptchaStore.Verify(captchaId, captchaCode, true) {
			reponse.FailWithErr(global.ErrValidateCaptche, ctx)
			ctx.Abort()
			return
		}
		ctx.Next()
	}
}
